package com.hk.huakangcompany.controller.es;

import com.hk.huakangcompany.commons.security.CommonResult;
import com.hk.huakangcompany.model.es.EsLoginLog;
import com.hk.huakangcompany.model.vo.Result;
import com.hk.huakangcompany.model.vo.ResultVO;
import com.hk.huakangcompany.service.es.EsLoginLogService;
import com.hk.huakangcompany.utils.EsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author zhe
 * @Create 2021/8/1/8:02
 * @State Es登录日志 前端控制器
 */
@RestController
@RequestMapping("/search")
public class EsLoginLogController {

    @Autowired
    private EsLoginLogService esLoginLogService;

    @PreAuthorize("hasAuthority('search:inquire')")
    @GetMapping("/pageList")
    public ResultVO pageList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            EsLoginLog loginLog
    ) throws IOException {
        page = (page-1)*limit;
        Map<String,Object> map = esLoginLogService.searchDocument(page,limit,loginLog);
        long total = (long) map.get("total");
        List<EsLoginLog> loginLogList = (List<EsLoginLog>) map.get("list");
        if (loginLogList.isEmpty()) {
            ResultVO resultVO = CommonResult.nullResultVO(total,loginLogList);
            return resultVO;
        }
        ResultVO resultVO = CommonResult.successResultVO(total,loginLogList);
        return resultVO;
    }

    /**
     * 单挑删除
     * @param id
     * @return
     * @throws IOException
     */
    @PreAuthorize("hasAuthority('search:delete')")
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) throws IOException {
        EsLoginLog esLoginLog = esLoginLogService.getDocumentInfo(EsUtil.ES_INDEX, String.valueOf(id));
        //       判断该账户是否在线中
        if (esLoginLog.getState() == 0) {
            Result result = CommonResult.nullResult("当前账户在线中，暂不能删除该条日志，请稍后重试！");
            return result;
        }
//        Es文档删除
        esLoginLogService.deleteDocumentInfo(EsUtil.ES_INDEX, String.valueOf(id), 1l);
        Result result = CommonResult.successResult("删除成功！");
        return result;
    }



}
